<template>
	<view class="content">
		<view class="head">
			<view class="head-left">
				<input v-model="adata.title" maxlength="30" placeholder="请输入标题（5~30个字）" @input="inputTitle" @blur="inputBlur" />
			</view>
			<view class="head-right">
				<view><i class="iconfont iconicon-test1"></i></view>
				<navigator hover-class="false" url="/pages/articleModule/cover">选封面</navigator>
			</view>
		</view>
		<!-- :style="'height: calc(100% - '+[inputOffsetBottom>0?((inputOffsetBottom)*2+100):((inputOffsetBottom)*2+120)]+'upx);'" -->
		<view class="edit" v-if="(adata.article_id && isRender) || (!adata.article_id && !isRender)" :style="'height: calc(100% - '+inputOffsetBottom+'px);'">
			<edit :inputOffsetBottom="inputOffsetBottom" @editInput="editInput" @getimg="getimg" :content="adata.content" ref="editRef"></edit>
			<view class="location" :style="{bottom:inputOffsetBottom+60+'px'}">
				<navigator :url="'../album/look-obj?obj='+obj" hover-class="none" class="location-item">
					<i class="iconfont iconbiaoqian"></i>
					<view class="location-text">{{Audience_text}}</view>
				</navigator>
				<navigator :url="'../album/send-aoe?aoe='+aoe" hover-class="none" class="location-item">
					<i class="iconfont icondaohang" style="font-size: 28upx;"></i>
					<view class="location-text">{{Release_text}}</view>
				</navigator>
				<view class="location-item" @click="chooseLocation">
					<i class="iconfont iconweizhi"></i>
					<view class="location-text">{{(adata.location && adata.location.length > 0) ? adata.location[0]['address']:'不显示位置'}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import edit from '../school/components/edit.vue';
	import util from '@/common/util.js';
	export default {
		components: {
			edit
		},
		data() {
			return {
				inputOffsetBottom: 0,
				windowHeight:0,
				adata: {
					title: '',
					content: '',
					location: [],
					Audience_scope: ['1'],
					Release_scope: ['1'],
					school_id: [],
					img_url: '',
					imgList:[]
				},
				imgData: {
					imgIndex: 0, //封面索引
					fromEditor: [], //富文本编辑器插入图片列表
					fromCover: []  //选择上传插入图片列表
				},
				Audience_text: '全部',
				Release_text: '全部',
				sign: '',
				isDraft: true, //是否是草稿发布
				aoe:1,
				obj:1,
				isRender: true, //是否不渲染富文本编辑器
			};
		},
		onNavigationBarButtonTap(e) {
			if (e.index == 0) {
				this.finish(1);
			} else {
				uni.navigateTo({
					url: '../album/drafts'
				})
			}
		},
		onReady() {
			uni.onWindowResize((res) => {
				this.windowHeight = res.size.windowHeight
				console.log('变化后的窗口宽度=' + res.size.windowWidth)
				console.log('变化后的窗口高度=' + res.size.windowHeight)
			})
			uni.onKeyboardHeightChange(res => {
				this.inputOffsetBottom = res.height
				console.log('软键盘高度=', res.height);
				if (res.height === 0) {
					this.focus = false
				} else {
					this.focus = true;
				}
			})
		},
		onBackPress() {
			this.adata = uni.getStorageSync('articlecontent');
			if (this.adata) {
				this.finish(2);
			} else {
				uni.removeStorageSync('articlecontent');
				uni.removeStorageSync('artImgs');
			}
		},
		onShow() {
			this.$api.apiPost('user/App/getsign').then(res => {
				if (res.data.code == 200) {
					this.sign = res.data.data.sign;
				}
			});
			let _this = this;
			uni.$once('look-obj', function(data) {
				console.log('Audience_scope',data.Audience_scope);
				_this.obj = data.Audience_scope
				_this.adata.Audience_scope = data.Audience_scope;
				_this.setstaut();
				uni.setStorageSync('articlecontent', _this.adata);
			})

			uni.$once('send_aoe', function(data) {
				let str = '';
				console.log('Release_scope',data.Release_scope);
				_this.adata.school_id = data.school_id;
				_this.adata.Release_scope = data.Release_scope;
				_this.setstaut();
				uni.setStorageSync('articlecontent', _this.adata);
			});
		},
		onLoad(e) {
			if (e.type == 'edit' && e.article_id) {
				this.isDraft = false;
				uni.setNavigationBarTitle({
					title: '编辑文章'
				})
				this.getDetail(e.article_id);
			} else if (e.type == 'draft') {
				this.getDetail(e.article_id);
			} else {
				// let adata = uni.getStorageSync('articlecontent');
				// if (adata) {
				// 	this.adata = adata;
				// }
				uni.setStorageSync('articlecontent',this.adata);
				this.isRender = false;
			}
			uni.setStorageSync('artImgs',this.imgData);
			this.setstaut();
		},
		methods: {
			getimg: function(e) {
				this.imgData = uni.getStorageSync('artImgs');
				this.imgData.fromEditor = e;
				uni.setStorageSync('artImgs',this.imgData);
			},
			/* 发布文章 */
			finish: function(type) {
				if (this.adata.title) {
					this.adata.title = this.adata.title.replace(/amp;/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/[, ]/g,'');
				}
				if (this.adata.content) {
					this.adata.content = this.adata.content.replace(/amp;/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
				}
				let imgArr = [];
				this.imgData = uni.getStorageSync('artImgs');
				if (this.imgData.fromEditor.length > 0) {
					this.imgData.fromEditor.forEach((item) => {
						imgArr.push(item);
					})
				}
				if (this.imgData.fromCover.length > 0) {
					this.imgData.fromCover.forEach((item) => {
						imgArr.push(item);
					})
				}
				let data = {
					content: this.adata.content,
					Release_scope: this.adata.Release_scope.join(','),
					title: this.adata.title,
					sign: this.sign,
					is_draft: type
				}
				if(typeof this.adata.Audience_scope == 'object'){
					data.Audience_scope = this.adata.Audience_scope.join(',')
				}else if(typeof this.adata.Audience_scope == 'string'){
					data.Audience_scope = this.adata.Audience_scope
				}
				if (imgArr.length > 0) {
					data.img_url = imgArr[this.imgData.imgIndex]
				}
				if (type == 1) {
					if (!data.title) {
						uni.showToast({
							title: '请填写文章标题',
							icon: 'none'
						});
						return
					} else {
						if (this.adata.title.length < 5) {
							this.inputBlur();
							return
						}
					}
					if (!data.content) {
						uni.showToast({
							title: '请填写文章内容',
							icon: 'none'
						});
						return
					}
				} else if (type == 2) {
					if (!data.title && !data.content) {
						uni.removeStorageSync('articlecontent');
						uni.removeStorageSync('artImgs');
						return
					}
				}
				if (this.adata.location && this.adata.location.length > 0) {
					var longitude = this.adata.location[0].longitude;
					var latitude = this.adata.location[0].latitude;
					data.coordinate = longitude + ',' + latitude;
					data.province_name = this.adata.location[0].province_name;
					data.city_name = this.adata.location[0].city_name;
					data.area_name = this.adata.location[0].name;
				}
				var url = 'user/article.Lists/issueArticle';
				if (this.adata.article_id) {
					data.article_id = this.adata.article_id
					url = 'user/article.Lists/eidtArticle';
				}
				console.log(data,"===--===",url);
				this.$api.apiPost(url, data).then(res => {
					uni.removeStorageSync('articlecontent');
					uni.removeStorageSync('artImgs');
					if (type == 1) {
						if (this.adata.article_id && this.isDraft) {
							if (res.data.code == 200) {
								uni.showToast({
									title: '发布成功',
									icon: 'none'
								});
							} else {
								uni.showToast({
									title: '发布失败',
									icon: 'none'
								});
							}
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
						if (res.data.code == 200) {
							setTimeout(function() {
								uni.reLaunch({
									url: '/pages/school/index'
								})
							}, 1000);
						}
					} else {
						if (res.data.code == 200) {
							uni.showToast({
								title: '保存草稿成功',
								icon: 'none'
							});
						} else {
							uni.showToast({
								title: '保存草稿失败',
								icon: 'none'
							});
						}
					}
				});
			},
			// 获取文章详情
			getDetail(article_id) {
				var data = {
					users_type: 1,
					is_user: 1,
					article_id: article_id
				}
				if (this.isDraft) {
					data.is_draft = 2;
				} else {
					// data.is_check = 3;
				}
				this.$api.apiPost('user/article.Lists/articleList', data).then(res => {
					if (res.data.code == 200) {
						var list = res.data.data.data;
						list.forEach((item) => {
							item['time'] = util.getLeftTime(item.creat_time);
							item.title = item.title.replace(/amp;/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/[, ]/g,'');
							if (item.content == null) {
								item.content = '';
							}
						})
						this.adata = list[0];
						// 如果有封面图片的话在this.imgData.fromCover插入封面图片，封面索引是图片列表的长度
						if(this.adata.img_url && this.adata.img_url != "undefined") {
							this.imgData.fromCover.push(this.adata.img_url);
							if (this.adata.imgList && this.adata.imgList.length > 0) {
								this.imgData.imgIndex = this.adata.imgList.length;
							}
							uni.setStorageSync('artImgs',this.imgData);
						}
						// this.$refs.editRef.insetCont(this.adata.content); //为了防止富文本编辑器在没有拿到值时已经进行渲染，强制清空富文本编辑器再次进行渲染
						this.dataFunc();
						this.$forceUpdate();
					} else {
						this.adata = {}
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						setTimeout(function() {
							uni.navigateBack({
								delta: 1
							})
						}, 1000);
					}
				})
			},
			// 初始化整理数据
			dataFunc() {
				this.adata['location'] = [];
				this.adata['Audience_scope'] = ['1'];
				this.adata['Release_scope'] = ['1'];
				this.adata['school_id'] = [];
				var cont = {};
				if (this.adata.coordinate) {
					cont['longitude'] = this.adata.coordinate.split(',')[0];
					cont['latitude'] = this.adata.coordinate.split(',')[1];
				}
				if (this.adata.province_name) {
					cont['province_name'] = this.adata.province_name;
				}
				if (this.adata.city_name) {
					cont['city_name'] = this.adata.city_name;
				}
				if (this.adata.area_name) {
					cont['name'] = this.adata.area_name;
				}
				if (JSON.stringify(cont) != '{}') {
					this.adata.location.unshift(cont);
				}
				uni.setStorageSync('articlecontent', this.adata);
			},
			// 选择发布范围 && 选择观看范围
			setstaut: function() {
				switch (this.obj) {
					case '1':
						this.Audience_text = '全部';
						break;
					case '2':
						this.Audience_text = '仅自己';
						break;
					case '3':
						this.Audience_text = '仅老师';
						break;
					case '4':
						this.Audience_text = '仅家长';
						break;
				}
				let str = '';
				this.aoe = []
				this.adata.Release_scope.forEach((item, key) => {
					console.log('item',item);
					this.aoe.push(item)
					switch (item) {
						case '1':
							str += '全部  ';
							break;
						case '2':
							str += '个人  ';
							break;
						case '3':
							str += '学校  ';
							break;
						case '4':
							str += '机构  ';
							break;
					}
				});
				
				console.log('aoe',this.aoe);
				if(this.aoe.length >= 3){
					str = '全部'
				}
				this.Release_text = str;
			},
			// 标题
			inputTitle: function(e) {
				this.adata.title = this.adata.title.replace(/[, ]/g,'');
				if (this.adata.title.length >= 30) {
					uni.showToast({
						title: '标题最多只能输入30个字',
						icon: 'none'
					});
				}
				uni.setStorageSync('articlecontent', this.adata);
			},
			// 标题失去焦点
			inputBlur() {
				if (this.adata.title.length < 5) {
					uni.showToast({
						title: '标题最少需输入5个字',
						icon: 'none'
					});
				}
			},
			/* 富文本内容 */
			editInput: function(data) {
				this.adata.content = data.detail.html;
				uni.setStorageSync('articlecontent', this.adata);
			},
			/* 选择地址 */
			chooseLocation: function() {
				var _this = this;
				uni.chooseLocation({
					success: res => {
						var area = res;
						var data = {
							key: '225BZ-7QO34-BZOUQ-DU247-YIGX7-IZF3M',
							get_poi: 0
						};
						var url = 'http://apis.map.qq.com/ws/geocoder/v1/?location=' + res.latitude + ',' +
							res.longitude;
						data.output = 'json';
						uni.request({
							type: 'get',
							dataType: 'jsonp',
							data: data,
							jsonp: 'callback',
							jsonpCallback: 'QQmap',
							url: url,
							success: function(json) {
								var toStr = JSON.stringify(json);
								var vstr = JSON.parse(json['data']);
								console.log(vstr,"====");
								area.province_name = vstr.result.address_component.province;
								area.city_name = vstr.result.address_component.city;
								_this.adata.location.unshift(area);
								_this.$forceUpdate();
								console.log(_this.adata.location, '==111=');
							},
							error: function(err) {
								uni.showToast({
									title: '服务端错误，请刷新浏览器后重试',
									icon: 'none'
								})
							}
						});
					}
				});
			}
		}
	};
</script>

<style lang="scss">
	.content {
		width: 100%;
		height: 100%;
		position: fixed;
		/* #ifdef H5 */
		top: 88upx;
		/* #endif */
		/* #ifndef H5 */
		top: 0;
		/* #endif */
	}

	.head {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20upx 30upx;
		border-bottom: 2upx solid #DCDFE6;
		height: 80upx;
		width: calc(100% - 60upx);
	}

	.head-left {
		width: 85%;
	}

	.head-right {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #666666;
	}

	.edit {
		width: 750upx;
		position: relative;
		height: auto;
	}

	.location {
		position: fixed;
		bottom: 120upx;

		.location-item {
			height: 50upx;
			line-height: 50upx;
			background: #00D5A2;
			display: table;
			border-radius: 10upx;
			padding: 0upx 8upx;
			margin: 20upx;
			color: #FFFFFF;

			view {
				display: inline-flex;
			}

			i {
				font-size: 24upx;
				margin-right: 8upx;
			}

			.location-text {
				font-size: 22upx;

			}
		}
	}
</style>
